<template>
  <div class="upload-invoice-model">
    <el-form>
    <el-form-item>
      <el-row :gutter="20">
        <el-col :span="3">
          <el-upload
            action=""
            :auto-upload="false"
            :show-file-list="false"
            accept=".zip"
            :on-change="handleUpload"
          >
            <el-button type="primary">上传ZIP自动解析</el-button>
          </el-upload>
        </el-col>
        <el-col :span="21">
          <el-button type="info" @click="fileList = []">清空</el-button>
        </el-col>
      </el-row>
    </el-form-item>
    </el-form>

    <el-table
      ref="table"
      v-if="fileList.length > 0"
      :data="fileList"
      style="width: 100%"
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="文件名" />
      <el-table-column prop="size" label="文件大小" />
    </el-table>

    <el-button
      v-if="fileList.length > 0"
      type="primary"
      @click="submitFiles"
      style="margin-top: 20px"
    >
      提交选中文件
    </el-button>
  </div>
</template>

<script>
import { parseInvoiceZIP,createInvoiceByZip } from '@/services/invoiceService';
export default {
  name: 'UploadInvoiceModel',
  data() {
    return {
      fileList: [],
    };
  },
  methods: {
    handleUpload(file) {
        console.log(file)
      if (file.raw.type == 'application/zip' || file.raw.type == 'application/x-zip-compressed') {
        const formData = new FormData();
        formData.append('file', file.raw);

        parseInvoiceZIP(formData)
        .then((response) => {
          console.log(response)
          this.fileList = response ;
          this.$message.success('解析成功');
        })
        .catch((error) => {
          console.log(error)
          this.$message.error(`解析失败: ${error.message}`);
        });

      }else{
        this.$message.error('请上传ZIP文件');
        return;
      }

      
    },
    submitFiles() {
      // 提交选中的文件到后台
      const selectedFiles = this.$refs.table.selection;
    //   console.log(selectedFiles)
      if (selectedFiles.length === 0) {
        this.$message.warning('请至少选择一个文件');
        return;
      }
      let fileListnew = []
      for (const fi of selectedFiles) {
        fileListnew.push(fi.name)
      }
      console.log(fileListnew)

      createInvoiceByZip(fileListnew)
        .then((response) => {
          console.log(response)
          this.fileList = [] ;
          this.$message.success('批量提交成功，还需要编辑确认进行入库');
        })
        .catch((error) => {
          console.log(error)
          this.$message.error(`提交失败: ${error.message}`);
        });
    },
  },
};
</script>

<style scoped>
.upload-invoice-model {
  padding: 20px;
}
</style>